const { User } = require('../model/dbModel/User')
const { SALT } = require('../config/systemconfig')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')

/**
 * 
 * @api {post} /user/register 用户注册
 * @apiName apiName
 * @apiGroup user
 * @apiVersion  1.0.0
 * @apiDescription 注册一个用户
 * 
 * 
 */
async function register(req, res) {
    const { username, password, usernickname, userrole } = req.body
    console.log(req.body);
    console.log(username, password)
    const model = await User.findOne({
            where: {
                username
            }
        })
        //判断用户是否存在
    if (model) {
        res.status(200).send({
            meta: {
                msg: "该用户已存在",
                status: 401
            }
        })
        return;
    }
    if(userrole != "student" &&userrole != "teacher"){
        res.status(200).send({
            meta: {
                msg: "没有该角色的预设",
                status: 401
            }
        })
        return;
    }
    //用户不存在，开始创建用户
    //加密
    const cryptpwd = bcrypt.hashSync(password, SALT);
    const createUser = await User.create({
        username: username,
        password: cryptpwd,
        usernickname: usernickname,
        userrole: userrole
    })
    res.status(200).send({
        data: {
            createUser
        },
        meta: {
            msg: "用户创建成功",
            status: 0
        }
    })
}

/**
 * 
 * @api {get} /user/login title23
 * @apiName 登录成功生成token返回给客户端
 * @apiVersion 1.0.0
 * @apiGroup user
 */
async function login(req, res) {
    const { username, password } = req.body

    if (username === undefined || password === undefined) {
        res.status(200).send("账户名或密码错误")
    }
    const model = await User.findOne({
            where: {
                username
            }
        })
        // 判断数据库是否存在该用户
    if (!model) {
        res.status(200).send({
            data: null,
            meta: {
                msg: "该用户不存在",
                status: 400
            }
        })
        return;
    }
    // 判断账号和密码是否正确
    var a = bcrypt.compareSync(password, model.password)
    if (model.username != username || !a) {
        res.status(200).send({
            data: null,
            meta: {
                msg: "账号密码不正确",
                status: 400
            }
        })
        return;
    }
    //登录成功生成token返回给客户端 
    const token = jwt.sign({ username }, 'D31');
    let user = model.toJSON();
    delete  user.password;
    delete user.createdAt;
    delete user.updatedAt
    res.status(200).send({
        token,
        user,
        meta: {
            msg: "登陆成功",
            status: 0
        }
    })
    return;

}

module.exports = {
    register,
    login
}